package com.cloud.basic.DefineClassLoader;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class DefineClassLoader extends ClassLoader {

    private String mPath;

    // 初始化自定义路径
    public DefineClassLoader(String mPath){
        this.mPath = mPath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // 文件名
        String fileName = getFileName(name);

        // 全路径和类名
        File file = new File(mPath,fileName);

        try {
            FileInputStream fis = new FileInputStream(file);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            int len = 0;

            while ((len = fis.read()) != -1) {
                bos.write(len);
            }
            byte[] data = bos.toByteArray();

            bos.close();
            fis.close();

            return defineClass(name, data,0,data.length);
        }  catch (IOException e) {
            e.printStackTrace();
        }

        return super.findClass(name);
    }

    // 获取类名
    public String getFileName(String name){
        int index = name.lastIndexOf(".");
        if (index==-1) {
            return name+".class";
        } else {
            return name.substring(index+1)+".class";
        }
    }

}
